//
//  LogCatInfoPlistHelper.m
//  LogCat
//
//  Created by Epoch on 2024/1/12.
//

#import "LogCatInfoPlistHelper.h"
#import "LogCat/LogCatHeader.h"

@implementation LogCatInfoPlistHelper

+ (void)checkInfoPlistKeys:(InfoPlistCheckResultBlock)block {
    if (block == nil) {
        return;
    }
    NSBundle *sdkBundle = [NSBundle bundleForClass:[LogCatInfoPlistHelper class]];
    NSDictionary *infoDict = [sdkBundle infoDictionary];
    if (!infoDict) {
        block(NO, @"未找到Info.plist");
    }
    NSArray *keysToCheck = @[@"CFBundleURLTypes",
                             @"ZX_CHANNEL_ID",
                             @"NSPhotoLibraryUsageDescription",
                             @"NSLocationAlwaysAndWhenInUseUsageDescription",
                             @"NSContactsUsageDescription",
                             @"NSAppTransportSecurity",
                             @"LSApplicationQueriesSchemes",
                             @"CFBundleURLTypes",
                             @"UIViewControllerBasedStatusBarAppearance"];
    
    NSMutableArray *missingKeys = [NSMutableArray array];
    for (NSString *key in keysToCheck) {
        if (!infoDict[key]) {
            [missingKeys addObject:key];
        }
    }
    
    if ([missingKeys count] == 0) {
        block(YES, @"info.plist权限配置自检测通过");
    } else {
        block(NO, [NSString stringWithFormat:@"Missing keys: %@", [missingKeys componentsJoinedByString:@", "]]);
    }
}

/// 从info.plist中加载配置数据
/// - Parameters:
///   - localModel: localModel description
///   - block: block description
+ (void)checkInfoWhenNeedLoadDataFromPlist:(LogCatLocalModel *)localModel block:(InfoPlistCheckResultBlock)block {
    if (block == nil || !localModel) {
        return;
    }

    NSBundle *sdkBundle = [NSBundle bundleForClass:[LogCatInfoPlistHelper class]];
    NSDictionary *infoDict = [sdkBundle infoDictionary];

    if (!infoDict) {
        block(NO, @"未找到Info.plist");
        return;
    }

    localModel.version = [sdkBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    localModel.bundleId = [sdkBundle bundleIdentifier];

    NSArray *keysToCheck = @[
        @"LogCat_AppId",
        @"LogCat_AppKey",
        @"LogCat_Scheme",
        @"LogCat_ValidYear",
        @"LogCat_ValidMonth",
        @"LogCat_ValidDay",
        @"LogCat_LocalUrl",
        @"LogCat_OssSuffix"];

    for (NSString *key in keysToCheck) {
        if (!infoDict[key]) {
            NSString *errorMessage = [NSString stringWithFormat:@"未找到%@", key];
            block(NO, errorMessage);
            return;
        }
        [localModel setValue:infoDict[key] forKey:key];
    }

    block(YES, @"成功加载Info.plist数据");
}

@end
